#! -*- coding:utf-8 -*-
import os
import json
import fcntl
import hashlib
import logging
import requests
from datetime import datetime, timedelta

from common.stats import MG_BIGBANG_COLL as mg
from common.transaction.model import Withdraw
from common.utils.tz import get_utc_date, local_now, utc_to_local

from django.core.management.base import BaseCommand
from django.conf import settings

_SINGLE_READS = 20000
_LOGGER = logging.getLogger('worker')


class Command(BaseCommand):

    def start(self):
        last_rec = mg.last_id.find_one({'type': 'withdraw'}) or {}
        last_id = last_rec.get('id', 0)
        items = Withdraw.query.filter(Withdraw.id>last_id).order_by(
            Withdraw.id).limit(_SINGLE_READS).all()
        for item in items:
            user_id = item.user_id
            withdraw_amount = float(item.price)
            target_type = item.target_type
            extend = json.loads(item.extend)
            info = extend['info']
            if target_type == 1: # alipay
                withdraw_no = (info.get('zfb') or info.get('no')).lower()
                withdraw_name = info.get('name', '')
            else:
                withdraw_no = info['no']
                withdraw_name = info.get('name', '')
            mg.withdraw_stats.update_one({
                'type': target_type,
                'no': withdraw_no,
                'name': withdraw_name,
                'user_id': user_id
            },{'$set': {
                'last_ts': item.created_at
            },'$inc': {
                'count': 1,
                'amount': withdraw_amount,
            },'$setOnInsert': {
                'created_at': item.created_at
            }}, upsert=True)
            # save daily stats
            today = utc_to_local(item.created_at)
            date_str = today.strftime('%Y-%m-%d')
            mg.withdraw_daily_stats.update_one({
                'day': date_str,
                'type': target_type,
                'no': withdraw_no,
                'name': withdraw_name,
                'user_id': user_id
            },{'$set': {
                'last_ts': item.created_at
            },'$inc': {
                'count': 1,
                'amount': withdraw_amount
            },'$setOnInsert': {
                'created_at': item.created_at
            }}, upsert=True)
            last_id = item.id
            mg.last_id.update_one({'type': 'withdraw'}, {'$set': {'id': last_id}}, upsert=True)
            print 'last_id', last_id

    def handle(self, days_ago=1, **kwargs):
        try:
            f = open('/tmp/flock_withdraw_stats', 'w')
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            self.start()
            fcntl.flock(f, fcntl.LOCK_UN)
        except Exception as e:
            print e
            _LOGGER.exception('user award error, %s', e)
